package tr.edu.ege.communicator.util;

import java.util.Vector;

import tr.edu.ege.communicator.Message;
import tr.edu.ege.communicator.exceptions.MessageQueueIsEmptyException;

/**
 * Holds the messages that peer receives.
 * 
 * @author Onur ULUSU
 * 
 */
public class MessageQueue {

	/**
	 * Message queue.
	 */
	private Vector<Message> mMessageQueue = new Vector<Message>();

	/**
	 * @return and deletes the next message from the message queue. If there is
	 *         no messages in the queue, throws an exception..
	 * @throws MessageQueueIsEmptyException
	 */
	public synchronized Message getNextMessageFromQueue()
			throws InterruptedException, MessageQueueIsEmptyException {
		// check whether the queue is empty or not..
		if (mMessageQueue.size() == 0) {
			CommunicatorLogger.log("Message queue is empty.");
			throw new MessageQueueIsEmptyException("Message queue is empty.");
		}
		// poping the first element of the queue..
		Message message = mMessageQueue.get(0);
		mMessageQueue.removeElementAt(0);
		return message;
	}

	/**
	 * Adds given message to the receiver's message queue
	 * 
	 * @param message
	 *            to be added to queue.
	 */
	public synchronized void addMessageToQueue(Message message) {
		mMessageQueue.add(message);
		CommunicatorLogger.log("Message is added to queue.");
	}

}
